package cn.stylefeng.guns.modular.single.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.StrUtil;
import cn.stylefeng.guns.modular.single.entity.DiseaseCS;
import cn.stylefeng.guns.modular.single.entity.DiseaseType;
import cn.stylefeng.guns.modular.single.entity.Patient;
import cn.stylefeng.guns.modular.single.entity.PatientEscalation;
import cn.stylefeng.guns.modular.single.mapper.DiseaseTypeDAO;
import cn.stylefeng.guns.modular.single.mapper.HqmsDao;
import cn.stylefeng.guns.modular.single.mapper.PatientDAO;
import cn.stylefeng.guns.modular.single.mapper.PatientEscalationDAO;
import cn.stylefeng.guns.modular.single.service.DiseaseTypeService;
import cn.stylefeng.guns.modular.single.service.HqmsService;
import cn.stylefeng.roses.kernel.config.modular.entity.SysConfig;
import cn.stylefeng.roses.kernel.config.modular.pojo.param.SysConfigParam;
import cn.stylefeng.roses.kernel.config.modular.pojo.param.SysConfigTypeParam;
import cn.stylefeng.roses.kernel.db.api.factory.PageFactory;
import cn.stylefeng.roses.kernel.db.api.factory.PageResultFactory;
import cn.stylefeng.roses.kernel.db.api.pojo.page.PageResult;
import cn.stylefeng.roses.kernel.dict.api.DictApi;
import cn.stylefeng.roses.kernel.dict.modular.entity.SysDict;
import cn.stylefeng.roses.kernel.dict.modular.entity.SysDictType;
import cn.stylefeng.roses.kernel.dict.modular.mapper.DictMapper;
import cn.stylefeng.roses.kernel.dict.modular.mapper.DictTypeMapper;
import cn.stylefeng.roses.kernel.dsctn.modular.controller.DatabaseInfoController;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class DiseaseTypeServiceImpl extends ServiceImpl<DiseaseTypeDAO, DiseaseType> implements DiseaseTypeService {
    @Resource
    private DiseaseTypeDAO dao;
    @Resource
    private DictMapper dictDao;
    @Resource
    private PatientDAO patientDAO;

    @Resource
    private HqmsService hqmsService;

    @Resource
    private PatientEscalationDAO patientEscalationDao;
    public List<SysDict> getInitConfigs(SysConfigTypeParam sysConfigTypeParam) {
        return dictDao.selectList(Wrappers.<SysDict>lambdaQuery().eq(SysDict::getStatusFlag,1).eq(SysDict::getDictShortCode, "single_group"));
    }

    public static Object getPropertyValue(Map<String,Object> obj, String propertyName) throws Exception {
        return obj.get(propertyName);
    }
    public  List<DiseaseType> datalist(String diseaseCode,String inNo){
        List<DiseaseType> list = dao.selectList(Wrappers.<DiseaseType>lambdaQuery().eq(DiseaseType::getDiseaseCode, diseaseCode).orderByAsc(DiseaseType::getOrderDesc));
        Patient patient =patientDAO.selectOne(Wrappers.<Patient>lambdaQuery().eq(Patient::getInNo, inNo));
        List<SysDict> dictList = dictDao.selectList(Wrappers.<SysDict>lambdaQuery()
                .eq(SysDict::getDictEncode, diseaseCode).ne(SysDict::getDictCode,"def"));
        if(patient.getStatus()==0){
            return newData(patient,list,dictList);
        }else{
            return getPatientEscalationData(patient,list,dictList);
        }

    }
    private List<DiseaseType> newData(Patient patient, List<DiseaseType> list , List<SysDict> dictList){
        List<Map<String,Object>> diseases =  hqmsService.getDiseaseCS(patient.getInNo());
        for (DiseaseType diseaseType : list) {
            if("数组".equals(diseaseType.getType())&&diseaseType.getDefaltValue()!=null){
                diseaseType.setDefaultValue(JSONArray.parseArray(diseaseType.getDefaltValue(),String.class));
            }
            try {
                if( !diseases.isEmpty()) {
                    Map<String,Object> diseaseCS = diseases.get(0);
                    Object obj = getPropertyValue(diseaseCS, diseaseType.getSubmitName().replaceAll("-", "_"));

                    if (obj != null) {
                        diseaseType.setDefaltValue((String) obj);
                    }
                }
            }catch (Exception e){
                System.out.println(e.getMessage());

            }

            if ("caseId".equals(diseaseType.getSubmitName())) {
                diseaseType.setDefaltValue(patient.getInNo());
            }
            if ("IDCard".equals(diseaseType.getSubmitName())) {
                diseaseType.setDefaltValue(patient.getIdCard());
            }
            if ("CM-0-2-1-2".equals(diseaseType.getSubmitName())) {
                diseaseType.setDefaltValue(patient.getSex());
            }
            if ("CM-0-2-4-1".equals(diseaseType.getSubmitName())) {
                diseaseType.setDefaltValue(DateUtil.format(patient.getInDate(), "yyyy-MM-dd HH:mm"));
            }
            if ("CM-0-2-4-2".equals(diseaseType.getSubmitName())) {
                diseaseType.setDefaltValue(DateUtil.format(patient.getOutDate(), "yyyy-MM-dd HH:mm"));
            }

            diseaseType.setDictList(dictList.stream()
                    .filter(p -> diseaseType.getSubmitName().equals(p.getDictShortCode())).collect(Collectors.toList())
            );
        }
        return list;
    }
    private List<DiseaseType> getPatientEscalationData(Patient patient, List<DiseaseType> list , List<SysDict> dictList){
        PatientEscalation patientEscalation =  patientEscalationDao.selectOne(Wrappers.<PatientEscalation>lambdaQuery().eq(PatientEscalation::getInNo, patient.getInNo()));
        JSONObject obj = JSONObject.parseObject(patientEscalation.getContent()) ;
        for (DiseaseType diseaseType : list) {
            Object val = obj.get(diseaseType.getSubmitName());
            if (val == null){
                diseaseType.setDefaltValue(null);
            }else{
                if("数组".equals(diseaseType.getType())){
                    diseaseType.setDefaultValue(JSONArray.parseArray(JSON.toJSONString(val) ,String.class));
                }else{
                    diseaseType.setDefaltValue( Convert.toStr(val,null));
                }
            }
            diseaseType.setDictList(dictList.stream()
                    .filter(p -> diseaseType.getSubmitName().equals(p.getDictShortCode())).collect(Collectors.toList())
            );
        }
        return list;
    }
    public List<DiseaseType> getDiseaseTypeList(String diseaseCode){
        return dao.selectList(Wrappers.<DiseaseType>lambdaQuery().eq(DiseaseType::getDiseaseCode, diseaseCode));
    }
    public PageResult<DiseaseType> findPage(SysConfigParam sysConfigParam) {

        LambdaQueryWrapper<DiseaseType> wrapper = Wrappers.<DiseaseType>lambdaQuery()
                .eq(sysConfigParam!=null&&StrUtil.isNotEmpty(sysConfigParam.getGroupCode()), DiseaseType::getDiseaseCode, sysConfigParam.getGroupCode());
        Page<DiseaseType> page = (Page)this.page(PageFactory.defaultPage(), wrapper);
        return PageResultFactory.createPageResult(page);
    }

    public DiseaseType detail(int id){
         DiseaseType diseaseType =dao.selectById(id);
        List<SysDict> dictList = dictDao.selectList(Wrappers.<SysDict>lambdaQuery()
                .eq(SysDict::getDictEncode, diseaseType.getDiseaseCode())
                .eq(SysDict::getDictShortCode,diseaseType.getSubmitName()));
        diseaseType.setDictList(dictList);
       if("数组".equals(diseaseType.getType())&&diseaseType.getDefaltValue()!=null){
            diseaseType.setDefaultValue(JSONArray.parseArray(diseaseType.getDefaltValue(),String.class));
        }
        return diseaseType;
    }
    public boolean edit(DiseaseType diseaseType){
        DiseaseType data =new DiseaseType();
        data.setId(diseaseType.getId());

      if("数组".equals(diseaseType.getType())&&diseaseType.getDefaultValue()!=null){
            diseaseType.setDefaltValue(JSON.toJSONString(diseaseType.getDefaultValue()));
        }
        if("def".equals(diseaseType.getDefaltValue())){
            data.setDefaltValue(null);
        }else {
            data.setDefaltValue(diseaseType.getDefaltValue());
        }
        return this.updateById(data);
    }
}
